package io.gitee.xyuesheng.day07;

import java.io.*;
import java.nio.file.FileVisitor;
import java.nio.file.Path;

public class Files {
    /**
     * 文件复制
     *
     * @param source-原来文件的路径
     * @param target-目标路径    copy("D:\\a.txt","E:||c.txt"
     */
    public static void copy(String source, String target) {
        //定义一个流，一个输入用来读，一个输出用来写
        try (
                InputStream is = new FileInputStream(source);
                OutputStream os = new FileOutputStream(target);
        ) {
            int c;
//            c=is.read();
//            复制少一个字节，复制会出错

            while ((c = is.read()) != -1) {
                os.write(c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件复制,在一个随机的地方中断复制
     *
     * @param source-原来文件的路径
     * @param target-目标路径    copy("D:\\a.txt","E:||c.txt"
     */
    public static void copyBreak(String source, String target) {
        //产生一个随机的中断位置(0<position<size)
        long size = new File(source).length();
        long randomSize = (long) (Math.random() * (size - 1)) + 1;

        System.out.println("复制了" + randomSize + "个字节");

        try (
                InputStream is = new FileInputStream(source);
                OutputStream os = new FileOutputStream(target);
        ) {
            int c;
//            c=is.read();
//            复制少一个字节，复制会出错

            while ((c = is.read()) != -1 && randomSize >= 0) {

                os.write(c);
                randomSize--;
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
